package core.cwm;

import java.util.List;

import core.access.Read;
import core.access.Right;
import core.access.Write;
import core.obj.Object;
import core.obj.Paycheck;
import core.obj.Payment;
import core.obj.Resume;
import core.obj.StaffingReq;
import core.obj.TimeReport;
import core.sub.Company;
import core.sub.Contractor;
import core.sub.ContractorAsEmployee;
import core.sub.Employee;
import core.sub.Subject;

public class ConstraintCondValidator implements Validator {

	@Override
	public boolean validate(Subject sub, Object obj, Right right) {
		if(sub instanceof Contractor) {
			return validate((Contractor)sub, obj, right);
		} else if(sub instanceof Company) {
			return validate((Company)sub, obj, right);
		} else if(sub instanceof Employee) {
			return validate((Employee)sub, obj, right);
		} else if(sub instanceof ContractorAsEmployee) {
			return validate(((ContractorAsEmployee)sub).asContractor(), obj, right) && validate(((ContractorAsEmployee)sub).asEmployee(), obj, right);
		}
		return false;
	}
	
	private boolean validate(Contractor contractor, Object obj, Right right) {
		if(right instanceof Read) {
			if(obj instanceof Resume) {
				return contractor.getResume().equals(obj);
			} else if(obj instanceof Paycheck) {
				return contractor.getPaychecks().contains(obj);
			} 
		} else if(right instanceof Write) {
			if(obj instanceof TimeReport) {
				CompanyRecord CDs = CompanyRecord.getInstance();
				Company C_obj = CDs.lookup(obj);
				Company C_cont = contractor.getResume().getCurrentCompany();
				if(C_cont != null)
					return C_cont.equals(C_obj);
				return false;
			} else if(obj instanceof Resume) {
				return contractor.getResume().equals(obj);
			}
		}
		return false;
	}
	
	private boolean validate(Company company, Object obj, Right right) {
		if(right instanceof Read) {
			if(obj instanceof Resume) {
				List<Company> companies =  ((Resume)obj).getCompanies();
				for(Company C: companies) {
					if(C.equals(company))
						continue;
					if(COISet.getInstance().isSameCOI(C, company))
						return false;
				}
				return true;
			}else if(obj instanceof TimeReport ||
					obj instanceof StaffingReq ||
					obj instanceof Payment)
				return CompanyRecord.getInstance().getCompanyDataSet(company).findObject(obj.getID()) != null;
		} else if(right instanceof Write) {
			if(obj instanceof TimeReport ||
					obj instanceof StaffingReq ||
					obj instanceof Payment)
				return CompanyRecord.getInstance().getCompanyDataSet(company).findObject(obj.getID()) != null;			
		}
		
		return false;
	}
	
	private boolean validate(Employee employee, Object obj, Right right) {
		if(right instanceof Read) {
			if(obj instanceof Resume)
				return true;
			else if(obj instanceof Paycheck)
				return true;
		} else if(right instanceof Write) {
			if(obj instanceof Paycheck)
				return true;
		}
		return false;
	}
}
